package filter;

import com.google.gson.Gson;
import model.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {
    private final Gson GSON = new Gson();

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
//        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
//        response.setHeader("Access-Control-Allow-Credentials", "true");

        String uri = request.getRequestURI();
        if (!request.getMethod().equals("OPTIONS") && auth(uri)) {
            Object login = request.getSession().getAttribute("admin");
            if (null == login) {
                response.getWriter().print(GSON.toJson(Result.reject("请登录后访问")));
                //response.setHeader("refresh:","2;url="+"http://localhost:8085/admin.html#/login");
                //response.setStatus(302);
                //response.setHeader("location", "http://localhost:8085/admin.html#/login");
                //response.sendRedirect("http://localhost:8085/admin.html#/login");
                return;
            }
        }
        chain.doFilter(req, resp);
    }

    private boolean auth(String uri) {
        switch (uri) {
            case "/api/admin/admin/login": case "/api/admin/admin/logoutAdmin":
                return false;
            default: return true;
        }
    }

    public void init(FilterConfig config) {

    }

}
